package com.demo.automic;

import lombok.Data;
import sun.misc.Unsafe;

import java.lang.reflect.Field;

public class UnsafeCas {

    public static void main(String[] args) throws NoSuchFieldException, IllegalAccessException {
        Field theUnsafe = Unsafe.class.getDeclaredField("theUnsafe");
        theUnsafe.setAccessible(true);
        Unsafe unsafe = (Unsafe) theUnsafe.get(null);
        System.out.println(unsafe);

        //1 获取域的偏移地址
        long idOffset = unsafe.objectFieldOffset(Teacher.class.getDeclaredField("id"));
        long nameOffset = unsafe.objectFieldOffset(Teacher.class.getDeclaredField("name"));
        Teacher teacher = new Teacher();
        //2执行cas操作
        //参数： 1 操作对象 偏移量 希望原来的值 交换的值
        unsafe.compareAndSwapInt(teacher,idOffset,0,1);
        //引用类型用compareAndSwapObject
        unsafe.compareAndSwapObject(teacher,nameOffset,""
                ,"lisi");//
        System.out.println(teacher);

    }


}
